package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.SessionConst;
import com.itheima.health.pojo.entity.Role;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.pojo.entity.User;
import com.itheima.health.service.UserService;
import com.itheima.health.pojo.dto.LoginDTO;
import com.itheima.health.utils.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     * TODO 登录和注册成功后，设置session时都要设置role权限
     * TODO 多种方式加密密码
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginDTO dto) {
        log.info("【登录】 dto:{}", dto);
        //调用service查询用户信息
        User user = userService.findByUsername(dto.getUsername());

        //用户不存在或密码不匹配则登录失败
        if (null == user || !EncryptUtil.equality(dto.getPassword(), user.getPassword())) {
            log.info("【登录】失败，userName:{}", dto.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        request.getSession().setAttribute(SessionConst.SESSION_USERNAME, user);
        Set<Role> roles = userService.getRoles((long) user.getId());
        //登录成功后，设置session时都要设置role权限
        request.getSession().setAttribute(SessionConst.SESSION_ROLE,roles);
        //模拟用户登录成功
        log.info("【登录】成功，userName:{}", user.getUsername());
        request.getSession().setAttribute(SessionConst.SESSION_USERNAME, user);

        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

}
